<template>
  <hi-row
    isColumn
    :wrap="false"
    class="viewcontainer"
    v-if="dataset && subDataSet"
  >
    <hi-col flex="340px">
      <hi-toolbar
        :calloutcofig="calloutcofig"
        :source="dataset"
        v-bind="toolbar"
        ref="dbtoolbar"
        :addOne="true"
        :disabled="dataset.isReadonly()"
      ></hi-toolbar>
      <btn-toolbar @callFunc="clickBtn" class="btn-toolbar"></btn-toolbar>

      <print
        :form-data="dataset.data[0]"
        :table-data="subDataSet.data"
        ref="print"
        v-if="dataset.data[0] && subDataSet.data"
      ></print>

      <hi-form
        :dataSource="dataset"
        ref="detailForm"
        :disabled="dataset.isReadonly()"
        :model="dataset.curRecord"
        v-bind="form"
      ></hi-form>
    </hi-col>
    <hi-col flex="auto" :min-height="200">
      <hi-table
        ref="detailTable"
        :dataSource="subDataSet"
        :isEdit="!subDataSet.isReadonly()"
        v-bind="dataTable"
        :model="subDataSet.data"
      ></hi-table>
    </hi-col>
    <el-dialog
      title="电子监管码"
      :visible.sync="supervisionCodeDialog"
      width="60%"
      :close-on-click-modal="false"
    >
      <inCode
        :dataset="codeList"
        :codeData="codeData"
        :subDataset="subDataSet"
        :auditData="dataset"
        v-if="supervisionCodeDialog"
      ></inCode>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="supervisionCodeDialog = false"
          >关 闭</el-button
        >
        <!-- <el-button type="primary">确 定</el-button> -->
      </span>
    </el-dialog>
  </hi-row>
</template>

<script>
import Print from "./print";
import BtnToolbar from "@/views/component/toolbar/index.vue";
import { HiForm, HiToolbar, HiTable, HiNumber, utils, dataHelper } from "hi-ui";
import viewBase from "../../base";
import { cloneDeep } from "lodash";
import toolbar from "@/hiuiDefaultConfig/toolbar";
import purchaseInspectConfig from "./dataset/inspectlist";
import purchaseInspectDetailConfig from "./dataset/detail";
import orderConfig from "../order/dataset/TransferOrder";
import audittag from "@/views/component/audittag";
import inCode from "@/views/supervisioncode/inCode";
import supervisionCodeCfg from "@/views/supervisioncode/inCode/dataset";
import bind from "lodash/bind";
export default {
  name: "inspectdetail",
  extends: viewBase,
  components: {
    HiForm,
    HiToolbar,
    HiTable,
    HiNumber,
    audittag,
    BtnToolbar,
    Print,
    inCode,
  },

  data() {
    let me = this;
    return {
      // 货架信息
      shelvesData: null,
      //监管码
      supervisionCodeDialog: false,
      //调单
      calloutcofig: {
        where: {
          criterionData: {
            join: "and",
            items: [
              {
                sign: "eq",
                name: "FSHOPDESCID",
                tablefilter: false,
                dataType: "dbString",
                value: bind(function () {
                  if (
                    this.dataset.data.length == 0 ||
                    !this.dataset.data[0].FSHOPDESCID
                  )
                    throw new Error("请选择店铺");
                  return this.dataset.data[0].FSHOPDESCID;
                }, me),
                enabled: true,
              },
            ],
          },
        },
        storeCfg: orderConfig,
        active: true,
        /* treeOption:{
                            "modelFile":"users",
                            label: "name",
                            children: "company"
                        }, */

        multiSelect: false,
        allOrderReturn: false,
        columns: [
          {
            name: "FNUMBER",
            label: "单号",
            width: 140,
          },
          {
            name: "FSUPPLIER",
            label: "供应商",
            width: 160,
          },
          {
            name: "FBUYAMOUNT",
            label: "采购数量",
            formType: "dbDouble",
            props: {
              precision: 2,
              // format: "0.00",
              "controls-position": "right",
            },
          },
          {
            name: "FINAMOUNT",
            label: "入库数量",
            formType: "dbDouble",
            props: {
              precision: 2,
              // format: "0.00",
              "controls-position": "right",
            },
          },
          {
            name: "FNINAMOUNT",
            label: "未入库数量",
            formType: "dbDouble",
            props: {
              precision: 2,
              // format: "0.00",
              "controls-position": "right",
            },
          },
        ],
        queryOption: {
          fields: [
            {
              name: "FNUMBER",
              element: "el-input",
              label: "单号",
            },
            {
              name: "FSUPPLIER",
              element: "el-input",
              label: "供应商",
            },
          ],
        },
        details: [
          {
            target: {
              id: "InspectEntity",
            }, //目标
            source: {
              id: "OrderEntity",
              modelFile: "purchase/order/dataset/OrderEntity_order.xml",
            },
            //来源
            // queryCdions: {}, //来源数据集查询条件
            updateFields: [], //更新字段
            limitEqualsFields: [], //相同字段
            uniqueFields: [], //主键
            returnFields: {
              FPURCHASINGNUMBER: "FNUMBER",
              FMONEY: "FMONEY",
              FSUPPLIER: "FSUPPLIER",
              FSUPPLIERID: "FSUPPLIERID",
            }, //返回字段
          },

          {
            target: {
              id: "InspectDetailEntity",
            }, //目标
            source: {
              id: "OrderDetailEntity",
              modelFile: "purchase/order/dataset/OrderDetailEntity_UnIns.xml",
            }, //来源
            queryCdions: {
              FNUMBER: function (rec) {
                return rec["FPURCHASINGNUMBER"];
              },
              FSHOPDESCID: function (rec) {
                return rec["FSHOPDESCID"];
              },
            }, //来源数据集查询条件
            updateFields: [], //更新字段
            limitEqualsFields: [], //相同字段
            uniqueFields: [], //主键
            returnFields: {
              // FNUMBER: "FNUMBER",
              FGOODSNUMBER: "FGOODSNUMBER",
              FBARCODE: "FBARCODE",
              FDESC: "FDESC",
              FBRAND: "FBRAND",
              FUNIT: "FUNIT",
              FWRKAMOUNT: "FSYAMOUNT",
              FPRICE: "FPRICE",
              FSPEC: "FSPEC",
              FPROCOMPANY: "FPROCOMPANY",
              FISRETAIL: "FISRETAIL",
              FSHELVESDESC: "FSHELVESDESC",
              FSHELVESID: "FSHELVESID",
            }, //返回字段
          },
        ],
      },

      //数据集
      dataset: null,
      //数据集配置
      datasetCfg: purchaseInspectConfig,
      //从表数据集
      subDataSet: null,
      //从表数据集配置
      subDatasetCfg: purchaseInspectDetailConfig,
      //从从表的数据集
      thridDataSet: null,
      //从从表的数据集配置
      thridDataSetCfg: supervisionCodeCfg,

      //数据桥梁
      dataBridge: new Map(),
      //数据表格
      dataTable: {
        isEdit: true,
        hasOperAdd: false,
        hasSelection: true,
        hasRowNumber: true,
        showSummary: true,
        columns: [
          {
            name: "FGOODSNUMBER",
          },

          {
            label: "电子监管码",
            width: 120,
            slot: [
              {
                element: "el-button",
                label: "电子监管码",
                props: {
                  size: "mini",
                  round: true,
                },
                handles: {
                  click: this.opencode,
                },
              },
            ],
          },

          {
            name: "FBARCODE",
          },
          {
            name: "FDESC",
          },

          {
            name: "FBRAND",
          },
          {
            name: "FSPEC",
          },
          {
            name: "FUNIT",
          },
          {
            width: "100",
            name: "FSHELVESDESC",

            /*   element: "hi-cascader-tab",
            props: {
              lookup: {
                modelFile: "shelves/dataset/ShelvesEntity.xml",
                // param: { FPID: "szdq" },
                param: { FPID: "KBJGLD", $pageIndex: -1, $pageSize: -1 },
                id: "FID",
                pid: "FPID",
                pathLabels: "FSHELVESDESC",
              },
              "show-all-levels": true,
              props: {
                value: "FDESC",
                label: "FDESC",
                leaf: "FLEAF",
                // emitPath:false,
                // multiple: true,
                // checkStrictly: true,
                lazy: true,
              },
            }, */
          },
          {
            name: "FPROCOMPANY",
          },
          /*     {
            name: "FISRETAIL",
            props: {
              disabled: true,
            },
          }, */

          {
            name: "FWRKAMOUNT",
            props: {
              min: 0,
              precision: 2,
            },
          },
          {
            name: "FAMOUNT",
            props: {
              min: 0,
              precision: 2,
            },
            summary: "sum",
          },
          {
            name: "FPRICE",
            props: {
              min: 0,
              format: "￥0.00",
              precision: 2,
            },
          },

          {
            name: "FMONEY",
            props: {
              format: "￥0.00",
              precision: 2,
            },
            summary: "sum",
          },

          {
            element: "el-date-picker",
            name: "PRODUCTIONDATE",
            props: {
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
            },
          },

          {
            element: "el-date-picker",
            name: "EXPIRATIONDATE",
            props: {
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
            },
          },
          {
            name: "FNOTE",
          },

          /*   {
            name: "FCREATEDATE",
          },

          {
            name: "FUSERID",
          }, */
        ],
      },
      toolbar: [],
      //表单配置
      form: {
        columnsTotal: 2,
        items: [
          {
            name: "FNUMBER",
          },
          {
            name: "FPURCHASINGNUMBER",
          },
          {
            name: "FSUPPLIER",
          },
          {
            name: "FSHOPDESC",
            element: "hi-select-grid",
            required: true,
            props: {
              selectOption: {
                loading: true,
                multiple: false,
                clearable: true,
                filterable: true,
                "allow-create": true,
                "collapse-tags": true,
              },
              lookup: {
                modelFile: "database/shop/dataset/ShopEntity.xml",
                label: "FDESC",

                tableprops: {
                  "show-header": false,
                  "max-height": 400,
                },
                returnFields: {
                  FSHOPDESC: "FDESC",
                  FSHOPDESCID: "FNUMBER",
                },
                columns: [
                  {
                    name: "FDESC",
                    label: "通用名称",
                  },
                ],
              },
            },
          },
          {
            name: "FNOTE",
            colspan: 2,
            props: {
              type: "textarea",
              autosize: { minRows: 4, maxRows: 4 },
              maxlength: 200,
            },
          },
          {
            name: "FUSERID",
          },
          {
            name: "FCREATEDATE",
          },

          {
            name: "FMONEY",
            props: {
              format: "￥0.00",
              precision: 2,
            },
          },

          {
            element: audittag,
            name: "FAUDIT",
          },
        ],
      },
    };
  },
  model: {
    prop: "value",
    event: "valuechange",
  },
  props: {
    value: {
      type: Object,
    },
  },

  computed: {},
  watch: {},
  methods: {
    clickBtn(methodName) {
      switch (methodName) {
        case "print":
          this.$refs.print.onPrint();
          break;
      }
    },
    //打开电子监管码
    opencode(evt, data, grid) {
      this.codeData = data;
      /*   if (!data.FAMOUNT) {
        this.$message.error("请选择入库数量");
        return;
      } else if (!(parseInt(data.FAMOUNT) == data.FAMOUNT)) {
        this.$message.error("请输入整数");
        return;
      } */

      this.codeList = grid.dataSource
        .getModel(data)
        .getChildStore("SupervisioncodeEntity_in");
      this.supervisionCodeDialog = true;
    },
    test() {
      debugger;
    },
    addDetail() {
      this.subDataSet.add({});
    },
    //更新金额
    updateFMONEY(data, store, options) {
      if (options == "add" || options.field == "FMONEY") {
        let allData = store.data,
          sum = 0;
        for (let i = 0; i < allData.length; i++) {
          let item = allData[i];
          sum = utils.number.accAdd(sum, item.FMONEY || 0);
        }
        this.dataset.data[0].FMONEY = sum;
      }
    },
    //更新货架
    updateShelves(model, store, options) {
      var _this = this;
      let val = options.value;
      let order = store.data[0].FPURCHASINGNUMBER;
      let param = new dataHelper.queryHelper.Param();
      let where = new dataHelper.queryHelper.Where({
        criterionData: {
          join: "and",
          items: [
            {
              sign: "eq",
              name: "FSHOPDESCID",
              tablefilter: false,
              dataType: "dbString",
              value: val,
              enabled: true,
            },
            {
              sign: "eq",
              name: "FNUMBER",
              tablefilter: false,
              dataType: "dbString",
              value: order,
              enabled: true,
            },
          ],
        },
      });
      where.setPage(-1, -1);
      param.setWhere(where);
      this.queryEntity(
        param,
        "purchase/order/dataset/OrderDetailEntity_UnIns.xml"
      ).then((res) => {
        for (var i = 0; i < res.dataPack.rows.length; i++) {
          if (res.dataPack.rows[i].FSHELVESDESC == null) {
            _this.subDataSet
              .getModel(_this.subDataSet.data[i])
              .set({ FSHELVESDESC: "" });
          } else {
            _this.subDataSet
              .getModel(_this.subDataSet.data[i])
              .set({ FSHELVESDESC: res.dataPack.rows[i]["FSHELVESDESC"] });
          }

          // .setCU
          // sta.cur.set({ FSHELVESDESC: res.dataPack.rows[i]["FSHELVESDESC"] });
        }
        // this.shelvesData = res.dataPack.rows;
      });
    },
  },
  //调单按钮
  created() {
    this.toolbar = cloneDeep(toolbar);
    this.toolbar.buttons.push({
      kind: "callout",
    });
  },

  mounted() {
    //创建主数据集
    this.dataset = this.createDataSet(this.datasetCfg); //this.$dsContainer.createDataSet(this.datasetCfg);
    // this.dataset.on("afterload", (val, item) => {
    //   debugger;
    // });
    this.dataset.on("beforesave", (store) => {
      //店铺
      if (store.data.length == 0) return;
      let shopDesc = store.data[0].FSHOPDESC,
        shopId = store.data[0].FSHOPDESCID;
      let subStore = store.models[0].getChildStore("InspectDetailEntity"),
        len = subStore.data.length;
      if (len == 0) return;
      for (let i = 0; i < len; i++) {
        let item = subStore.data[i];
        item.FSHOPDESC = shopDesc;
        item.FSHOPDESCID = shopId;
        /*    let subSubStore = subStore.models[i].getChildStore(
          "SupervisioncodeEntity_in"
        );
        if (
          subSubStore.data.length != 0 &&
          subSubStore.data.length != item.FAMOUNT
        ) {
          this.$message.error("电子监管码与入库数量不一致");
          store.cancel = true;
          return;
        } */
      }
    });

    this.dataset.on("afterchange", (model, store, options) => {
      if (options.field == "FSHOPDESCID" && me.subDataSet.data.length != 0) {
        this.updateShelves(model, store, options);
        // this.clearable();
      }
    });
    //创建从数据集
    this.subDataSet = this.createDataSet(this.subDatasetCfg, this.dataset);
    let me = this;
    this.subDataSet.on("afterchange", (model, store, options) => {
      me.updateFMONEY(model.data, store, options);
    });
    this.subDataSet.on("afteradd", (data, store, options) => {
      me.updateFMONEY(data, store, "add");
    });
    //创建从从数据集
    this.thridDataSet = this.createDataSet(
      this.thridDataSetCfg,
      this.subDataSet
    );

    //设置数据与组件的关系
    this.dataBridge.set(this.dataset, ["detailForm", "detailTable"]);
    this.dataBridge.set(this.subDataSet, []);

    this.flowConfig = { dataset: this.dataset };
    if (this.$route.query.id) {
      this.dataset.load({
        FID: this.$route.query.id,
      });
    }
    console.log("table----------", this.subDataSet);
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scope>
</style>

